import { backToLoginPage, clearLoginInfo } from "@/authorization/useAuthorization"
import type { RequestConfigExtra } from "@/http/types"
import { isFunction, message } from "@/utils"

/**
 * 请求结果结构定义
 */
export interface ResponseData<T = any> {
    status: boolean
    code: string
    message: string
    data: T
}

/**
 * 对请求结果进行自定义处理
 */
export function useAxios() {
    /**
     * 对结果进行默认处理
     * @param data 返回结果
     * @param options 请求配置
     */
    const handleResponseData = (data: ResponseData<any>, options: RequestConfigExtra) => {
        // 正常返回
        if (data.status === true) {
            return handleSuccess(data, options)
        } else {
            return handleError(data, options)
        }
    }

    /**
     * 后台处理成功，前端响应
     * @param data 返回数据
     * @param options 请求配置
     */
    const handleSuccess = (data: ResponseData<any>, options: RequestConfigExtra) => {
        const { success } = options
        if (success === true) {
            message.success(data.message)
        } else if (isFunction(success)) {
            ;(success as Function)(data)
        }
        return data
    }

    /**
     * 后台处理失败，前端响应
     * @param data 返回数据
     * @param options 请求配置
     */
    const handleError = (data: ResponseData<any>, options: RequestConfigExtra) => {
        const { error } = options
        // 登录失效
        if (data.code === "401") {
            clearLoginInfo()
            backToLoginPage(false)
            message.error("登录已失效")
            return data
        }
        if (error === true) {
            message.error(data.message)
        } else if (isFunction(error)) {
            ;(error as Function)(data)
        }
        return data
    }

    return { handleResponseData }
}
